// src/context/AuthContext.ts

import { createContext, useContext, useState } from 'react';
import axios from 'axios';
import { useDispatch, useSelector } from 'react-redux';
import {setUser} from '../store/model/counter'
import React from 'react';

interface AuthState {
  permissions: string[];
  login: any;
}

const AuthContext = createContext<AuthState | null>(null);

const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const dispatch = useDispatch();
    const authList=useSelector((store:any)=>store.counter.sidebarList)
    const [isAuthenticated,setIsAuthenticated]=useState(false)
    const [permissions, setPermissions] = useState<string[]>([]);

    const login = async (mobile: string, password: string) => {
        let { data: { code, msg, user, accessToken, secondToken } } = await axios.post("http://localhost:3000/login", {
            password: password,
            mobile: mobile
        })
        if (code === 200) {
            dispatch(setUser(user))
            localStorage.setItem('token', accessToken)
            localStorage.setItem('secondToken', secondToken)
            if (user.authentication ==null) {
                localStorage.removeItem('authentication')
            }else{
                localStorage.setItem('authentication', user.authentication)
            }
            await axios.post("http://localhost:3000/addOperation",{
                feature:'登录',
                operation:user.username,
            })
        }
        setIsAuthenticated(true);
        setPermissions(authList);
    }

    return (
        <AuthContext.Provider value={{ permissions, login }}>
        {children}
        </AuthContext.Provider>
    );
};

export { AuthContext, AuthProvider };

const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

export default useAuth;